<template>
	<div>
		<game-box>
			<template #config>
				<div class="h-full w-full bg-[#2a364f] px-[12px] py-[16px]">
					<template v-if="!isDesktop">
						<BetAmount
							:type="type"
							:isRuning="isRuning"
							:isDisabled="isDisabled"
							:showMax="maxbet"
							:amount="amount"
							@changeMoneyDisabled="changeMoneyDisabled"
							@changeAmount="changeAmount" />
						<base-button
							class="w-full h-[52px] flex justify-center items-center bg-[#7864FF] text-white app-font-bold rounded-md text-[16px] f-style b-shadow random-style"
							v-if="!showBet"
							:disabled="randomLoading"
							@click="randomClick">
							{{ $t('miniGames.pickRandomTile') }}
						</base-button>
						<div class="h-group-t" v-if="!showBet"></div>
						<StartBtn
							v-if="showBet"
							@handleClick="handleStart"
							:type="type"
							stopIcon="mines"
							:isRuning="isRuning"
							:stoping="stoping"
							:isDisabled="isBtnAutoDisabled || isMoneyDisabled" />
						<base-button
							style="margin-top: 12px"
							class="w-full h-[52px] flex justify-center items-center bg-[#7864FF] text-white app-font-bold rounded-md text-[16px] f-style b-shadow"
							v-else
							type="primary"
							:disabled="!selectedArr.length"
							@click="handleShowCash">
							{{ $t('miniGames.cashout') }}
						</base-button>
					</template>
					<SwitchTab
						v-if="isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="isRuning"
						:prohibit="!showBet"
						:cache="false"
						@changeMode="changeMode" />
					<div class="h-group-t"></div>
					<BetAmount
						v-if="isDesktop"
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						:showMax="maxbet"
						:amount="amount"
						@changeMoneyDisabled="changeMoneyDisabled"
						@changeAmount="changeAmount" />
					<div class="h-group-t" v-if="isDesktop"></div>
					<MinesCount
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						:count="mines"
						:showBet="showBet"
						@changeMines="changeMines" />
					<div class="h-group-t" v-if="!showBet || type === 'auto'"></div>
					<div v-if="type === 'manual' && !showBet">
						<div class="yingli">
							<span class="yingli1 text-[14px]">
								{{ $t('miniGames.totalProfit') }}（{{ minesMultiplier }}x）
							</span>
							<span class="yingli2 text-[12px]">
								<base-amount :value="value" :currency="currency" hide-currency reverse-fiat />
							</span>
						</div>
						<n-input
							size="large"
							class="flex-1 h-[40px] mt-[4px] bg-[#3e4c68] input-style rounded-[4px]"
							:disabled="isDisabled"
							v-model:value="value"
							readonly>
							<template #suffix>
								<BaseCurrencyFait />
							</template>
						</n-input>
						<div class="h-group-t" v-if="isDesktop"></div>
					</div>
					<template v-if="type === 'auto'">
						<LoopCount
							@changeLoop="changeLoop"
							:type="type"
							:loopNum="loopNum"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
						<div class="h-group-t"></div>
						<profit-percentage
							:isRuning="isRuning"
							:title="$t('miniGames.onwin')"
							type="profitPer"
							:isDisabled="isDisabled"
							@change="changeProfitPercentage" />
						<div class="h-group-t"></div>
						<profit-percentage
							:isRuning="isRuning"
							:isDisabled="isDisabled"
							:title="$t('miniGames.onloss')"
							type="lossPer"
							@change="changeLossPercentage" />
						<div class="h-group-t"></div>
						<stop-profitable
							@changeProfitable="changeProfitable"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
						<div class="h-group-t"></div>
						<loss-suspension
							@changeLoss="changeLoss"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
					</template>
					<template v-if="isDesktop">
						<base-button
							class="w-full h-[52px] flex justify-center items-center bg-[#7864FF] text-white app-font-bold rounded-md text-[16px] f-style b-shadow random-style"
							v-if="!showBet"
							:disabled="randomLoading"
							@click="randomClick">
							{{ $t('miniGames.pickRandomTile') }}
						</base-button>
						<div class="h-group-t" v-if="!showBet"></div>
						<StartBtn
							v-if="showBet"
							@handleClick="handleStart"
							:type="type"
							stopIcon="mines"
							:isRuning="isRuning"
							:stoping="stoping"
							:isDisabled="isBtnAutoDisabled || isMoneyDisabled" />
						<base-button
							class="w-full h-[52px] flex justify-center items-center bg-[#7864FF] text-white app-font-bold rounded-md text-[16px] f-style b-shadow"
							v-else
							type="primary"
							:disabled="!selectedArr.length"
							@click="handleShowCash">
							{{ $t('miniGames.cashout') }}
						</base-button>
					</template>
					<SwitchTab
						v-if="!isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="isRuning"
						:cache="false"
						:prohibit="!showBet"
						@changeMode="changeMode" />
				</div>
			</template>
			<template #content>
				<div ref="gameContent" class="h-full w-full bg-[#1B2538]"></div>
			</template>
		</game-box>
		<result-dialog
			:showDialog="showResult"
			:betId="resultBetId"
			:gameObj="minesGames"
			gameType="mines"
			@close="closeResultDialog" />
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { BaseButton, BaseAmount, BaseCurrencyFait } from '@/components/base'
import { NInput } from 'naive-ui'
import GameBox from '../components/game-box/index.vue'
import StartBtn from '../components/common/start-button.vue'
import BetAmount from '../components/common/bet-amount.vue'
import SwitchTab from '../components/common/switch-tab.vue'
import LoopCount from '../components/common/loop-count.vue'
import stopProfitable from '../components/common/stop-profitable.vue'
import lossSuspension from '../components/common/loss-suspension.vue'
import profitPercentage from '../components/common/profit-percentage.vue'
import MinesCount from './mines-count.vue'
import ResultDialog from '../components/dialog/result.vue'
import { loadJs, showError, message, getCurrencyIcon } from '@/utils'
import { isDesktop } from '@/hooks'
import {
	playMines,
	playMinesField,
	playAutoMines,
	exchangeMines,
	gameEndSettled,
	minesUnsettled
} from '@/api/third/mini-games'
import { useWalletStore, useAccountStore, useAppStore } from '@/store'
import { AccountShowType } from '@/types'
import { eventBus } from '@/views/games/eventBus'
import { qlaunchUrl } from '../getUrlT'
import {
	transferToNumber,
	transformationAmount,
	getDecimalPlaces,
	clacProfit,
	calculateProfitLoss
} from '../util'
import { delayGameTime, accelerateTimeInter, delayTimeInter } from '@/views/games/config'

const token = computed(() => accountStore.token)
const accountStore = useAccountStore()
const walletStore = useWalletStore()
const appStore = useAppStore()
const currency = computed(() => walletStore.balanceCur?.currency)
const type = ref('manual')
const isRuning = ref(true)
const isDisabled = ref(true)
const stoping = ref(false)
const isBtnAutoDisabled = ref(true)
const isMoneyDisabled = ref(false)
const value = ref<any>('0')
const mines = ref(3)
const mute = ref(false)
const maxbet = ref(false)
const rocket = ref(false)
const loopNum = ref(0)
const profit = ref<string | number>(0)
const loss = ref<string | number>(0)
const amount = ref<string | number>(0)
const autoOneAmount = ref<string | number>(0)
const profitPer = ref<any>({ value: 0, active: 'rest' })
const lossPer = ref<any>({ value: 0, active: 'rest' })
const timeInter = ref(delayTimeInter)
const showResult = ref(false)
const minesMultiplier = ref<any>(1)
const resultBetId = ref('')
const showBet = ref(true)
const randomLoading = ref<boolean>(false)
const gameContent = ref(null)
//游戏状态
// let gameStatus = false
let interval: any = null
// 累计盈利亏损
const profitLossTotal = ref(0)
let pLTotal: any = 0
let currentId = ''
let PayoutType: any = null
// 设置选中多个结果
let resultArr: any = []
// 设置选中多个结果
let selectedArr: any = ref([])
// const minesGames = ref<any>(null)
let minesGames: any = null
let languageMap: any = null
watch(
	token, // 监听计算属性 token
	(newVal: any, oldVal: any) => {
		if (newVal !== oldVal) {
			qlaunchUrl(initGame)
		}
	}
)
watch(
	() => appStore.lang,
	(val: string) => {
		minesGames?.setLanguage(languageMap?.[val])
	}
)
watch(
	() => walletStore.balanceCur?.currency,
	() => {
		minesGames && minesGames.setCurrencyIcon(getCurrencyIcon())
	}
)
onMounted(() => {
	qlaunchUrl(initGame)
	eventBus.on('changeRocket', (val: any) => {
		console.log(val)
		rocket.value = val
		minesGames?.setAccelerationMode(val)
		timeInter.value = val ? accelerateTimeInter : delayTimeInter
	})

	eventBus.on('changeMaxBet', (val: any) => {
		console.log(val)
		maxbet.value = val
	})
	eventBus.on('changeMute', (val: boolean) => {
		console.log(val)
		mute.value = val
		minesGames.setSoundEffect(!val)
	})
})
onUnmounted(() => {
	restTimeAuto()
	// 在组件卸载时移除监听器
	eventBus.off('changeRocket', () => {
		// 空的回调函数
	})
	eventBus.off('changeMaxBet', () => {
		// 空的回调函数
	})
	eventBus.off('changeMute', () => {
		// 空的回调函数
	})
})
const changeMoneyDisabled = (status: boolean) => {
	isMoneyDisabled.value = status
}
const restTimeAuto = (auto = false) => {
	interval && clearTimeout(interval)
	isRuning.value = false
	isDisabled.value = false
	if (auto) {
		message.success('自动投注完成', { duration: 5000 })
	}
}
const gameEnd = () => {
	if (!currentId) return
	setTimeout(() => {
		gameEndSettled({
			round: currentId
		})
	}, 500)
}
const initGame = async () => {
	// 查询是否有未结束的
	const res = await minesUnsettled()
	loadJs('/gameLib.js').then((originalGameLib: any) => {
		PayoutType = originalGameLib.PayoutType
		let Language = originalGameLib.Language
		languageMap = {
			zh: Language.ZH,
			zhTW: Language.zhTW,
			en: Language.EN
		}
		minesGames = new originalGameLib.MinesGame({
			parentElement: gameContent.value,
			backgroundColor: '#1B2538',
			language: languageMap[appStore.lang],
			currencyIcon: getCurrencyIcon(),
			backgroundAlpha: 1,
			soundEffect: true,
			fullScreen: false,
			gameMode: PayoutType.MANUAL,
			minesCount: mines.value,
			onManualGameSquareClick: onManualGameSquareClick, //手动下点击方块的回调
			onAutoGameSquareClick: onAutoGameSquareClick, //在自动下点击方块的回调
			onCashOutOverClick: onCashOutOverClick, //兑现回调
			onGameLoadEnd: () => onGameLoadEnd(res?.data)
		})
	})
}
// 未完成游戏状态恢复
const incompleteGameRecovery = (data: any) => {
	if (!data) return
	currentId = data.id
	isDisabled.value = true
	showBet.value = false
	selectedArr.value = []
	amount.value = data.amount
	const { rounds, minesCount } = data.state
	minesMultiplier.value = rounds?.[rounds?.length - 1]?.payoutMultiplier || 0
	minesMultiplier.value = Number(minesMultiplier.value).toFixed(2)
	mines.value = minesCount
	//重置游戏
	minesGames.resetAll()
	// 开始游戏
	minesGames.gameStart(true)
	//展示这个钻石
	rounds?.forEach((item: any) => {
		selectedArr.value.push(item.field)
		console.log(item.field, minesGames, 'minesGames')
		minesGames.ShowDiamond(item.field)
	})
	const now = selectedArr.value.length
		? minesGames.getMinesMultiplier(selectedArr.value.length, Number(mines.value))
		: 0
	//修改收益
	changeProfit(
		now,
		minesGames.getMinesMultiplier(selectedArr.value.length + 1, Number(mines.value))
	)
	pLTotal = 0
	calculateProfit()
}
const onGameLoadEnd = (data: any) => {
	isRuning.value = false
	isDisabled.value = false
	isBtnAutoDisabled.value = false
	if (data && type.value === 'manual') {
		minesGames.setSoundEffect(false)
		incompleteGameRecovery(data)
		minesGames.setSoundEffect(true)
	}
}
//修改收益
const changeProfit = (nowProfit: any, nextProfit: any) => {
	console.log(nowProfit, nextProfit, 'nowProfit')
	minesMultiplier.value = nowProfit
}
// 计算盈利
const calculateProfit = () => {
	const multiplier = minesMultiplier.value || 0
	if (multiplier) {
		pLTotal += Number(amount.value) * Number(multiplier) - Number(amount.value)
		value.value = transferToNumber(pLTotal.toFixed(getDecimalPlaces()))
	} else {
		pLTotal = 0
		value.value = 0
	}
}
const onManualGameSquareClick = async (resultIndex: number, randomStatus: boolean = false) => {
	console.log(resultIndex, randomStatus, 'resultIndex')
	try {
		randomLoading.value = true
		const { data } = await playMinesField({
			round: currentId,
			field: resultIndex
		}).finally(() => {
			randomLoading.value = false
		})
		if (data.state.mines && data.state.mines.length) {
			// 如果有炸弹，结束游戏
			showBet.value = true
			selectedArr.value = []
			isDisabled.value = false
			// walletStore.getBalance(0)
			changeProfit(0, 0)
			calculateProfit()
			if (randomStatus) {
				//展示这个炸弹
				minesGames.ShowMines(data.state.mines, resultIndex)
			}
			gameEnd()
			return { isSuccess: true, isMine: true, allMines: data.state.mines }
		} else {
			selectedArr.value.push(resultIndex)
			//修改收益
			changeProfit(
				minesGames.getMinesMultiplier(selectedArr.value.length, Number(mines.value)),
				minesGames.getMinesMultiplier(selectedArr.value.length + 1, Number(mines.value))
			)
			calculateProfit()
			if (randomStatus) {
				//展示这个钻石
				minesGames.ShowDiamond(resultIndex)
			}
			return { isSuccess: true, isMine: false, allMines: [] }
		}
	} catch {
		return { isSuccess: false, isMine: false }
	}
}
const onAutoGameSquareClick = (resultIndex: number) => {
	console.log('点击结果')
	if (resultArr.includes(resultIndex)) {
		// 如果存在，移除该值
		resultArr = resultArr.filter((item: any) => item !== resultIndex)
		console.log(resultArr)
	} else {
		resultArr.push(resultIndex)
		console.log(resultArr)
	}
	console.log(resultIndex)
	// 如果resultArr没有值或者值为空
	if (resultArr.length !== 0) {
		isBtnAutoDisabled.value = false
	} else {
		isBtnAutoDisabled.value = true
	}
}
const onCashOutOverClick = (data: any) => {
	console.log(data)
	console.log(currentId)
	resultBetId.value = currentId
	showResult.value = true
	console.log('兑现回调1')
	// walletStore.getBalance(0)
}

const handleShowCash = async () => {
	// 手动兑现
	const { data } = await exchangeMines({
		round: currentId
	})
	isDisabled.value = false
	showBet.value = true
	const multiplier = minesGames.getMinesMultiplier(selectedArr.value?.length, Number(mines.value))
	minesGames &&
		minesGames.cashOutOver(
			data.state.mines,
			clacProfit(data),
			multiplier + '',
			selectedArr.value?.length || 0
		)
	gameEnd()
	console.log('兑现回调手机')
	// walletStore.getBalance(0)
}

const closeResultDialog = () => {
	showResult.value = false
}
const randomClick = () => {
	const randomNum: any = generateUniqueRandom()
	onManualGameSquareClick(randomNum, true)
}
// 生成 0 到 24 之间的随机数
function generateUniqueRandom() {
	if (selectedArr.value.length === 25) {
		console.log('所有数字都已经出现过了')
		return null // 或者抛出异常，根据具体需求处理
	}

	let randomNum
	do {
		randomNum = Math.floor(Math.random() * 25)
	} while (selectedArr.value.includes(randomNum))

	selectedArr.value.push(randomNum)
	return randomNum
}
const handleStart = async () => {
	profitLossTotal.value = 0
	if (type.value === 'auto') {
		console.log('auto')
		if (isRuning.value) {
			//点击停止自动投注
			// walletStore.getBalance(0)
			stoping.value = true
			setTimeout(() => {
				//重置游戏
				minesGames.resetAll()
				// 开始游戏
				minesGames.gameStart(true)
				stoping.value = false
				restTimeAuto(true)
			}, delayGameTime)
		} else {
			if (!resultArr.length) return
			message.success('自动投注开始', { duration: 5000 })
			isDisabled.value = true
			isRuning.value = true
			autoOneAmount.value = amount.value

			if (loopNum.value === 0) {
				atuoBetMines('all')
			}
			if (loopNum.value > 0) {
				atuoBetMines('count')
				loopNum.value--
				if (loopNum.value <= 0) {
					isRuning.value = false
					interval && clearTimeout(interval)
					message.success('自动投注完成', { duration: 5000 })
					minesGames.resetAll()
					// 开始游戏
					minesGames.gameStart(true)
				}
			}
		}
	} else {
		isDisabled.value = true
		isRuning.value = true
		selectedArr.value = []
		// console.log('开始')
		await betMines()
		// await playGame()
		//修改收益
		changeProfit(0, minesGames.getMinesMultiplier(1, Number(mines.value)))
		pLTotal = 0
		calculateProfit()
	}
}

const atuoBetMines = async (loop: string = '') => {
	if (!accountStore.token) {
		accountStore.showAccount(AccountShowType.login)
		return
	}
	if (stoping.value) return
	minesGames.resetAll()
	// 开始游戏
	minesGames.gameStart(true)
	try {
		const { data } = await playAutoMines({
			amount: transformationAmount(amount.value),
			currency: walletStore.balanceCur?.currency,
			minesCount: mines.value,
			field: resultArr
		})
		currentId = data.id
		setTimeout(() => {
			minesGames.ShowAllResult(data.state.mines)
			let resultArrHasMines: boolean = false
			for (let value of resultArr) {
				if (data.state.mines.includes(value)) {
					// 如果有任意一个值在 resultArr 中，结束游戏
					resultArrHasMines = true
					gameEnd()
					break
				}
			}
			if (!resultArrHasMines) {
				const multiplier = minesGames.getMinesMultiplier(resultArr.length, Number(mines.value))
				minesGames &&
					minesGames.cashOutOver(
						data.state.mines,
						clacProfit(data),
						multiplier + '',
						resultArr.length
					)
				gameEnd()
			}

			// 计算是否达到盈亏阈值
			if (
				calculateProfitLoss(data, {
					type,
					amount,
					profitPer,
					lossPer,
					profit,
					loss,
					profitLossTotal,
					autoOneAmount
				})
			) {
				restTimeAuto()
				setTimeout(() => {
					minesGames.resetAll()
					minesGames.gameStart(true)
				}, delayGameTime)
				return
			}
			// 自动投注状态
			if (loop === 'all' && isRuning.value) {
				interval = setTimeout(() => {
					atuoBetMines(loop)
				}, timeInter.value)
			}
			if (loop === 'count' && loopNum.value > 0 && isRuning.value) {
				interval = setTimeout(() => {
					atuoBetMines(loop)
					loopNum.value--
					if (loopNum.value <= 0) {
						restTimeAuto(true)
						minesGames.resetAll()
						// 开始游戏
						minesGames.gameStart(true)
					}
				}, timeInter.value)
			}
			// 自动次数停止
			if ((loop === 'count' && loopNum.value <= 0) || !isRuning.value) {
				setTimeout(() => {
					minesGames.resetAll()
					minesGames.gameStart(true)
				}, delayGameTime)
			}
		}, 1000)
	} catch (error: any) {
		showError(error)
		interval && clearTimeout(interval)
		isDisabled.value = false
		isRuning.value = false
	}
}
const betMines = async () => {
	if (!accountStore.token) {
		accountStore.showAccount(AccountShowType.login)
		return
	}
	try {
		const { data } = await playMines({
			amount: transformationAmount(amount.value),
			currency: walletStore.balanceCur?.currency,
			minesCount: mines.value
		}).finally(() => {
			isRuning.value = false
		})
		showBet.value = false
		currentId = data.id
		//重置游戏
		minesGames.resetAll()
		// 开始游戏
		minesGames.gameStart(true)
		// walletStore.getBalance(0)
	} catch (error: any) {
		showError(error)
		isDisabled.value = false
		isRuning.value = false
	}
}

const changeMines = (val: number) => {
	mines.value = val
	minesGames.updateMinesCount(mines.value)
}
const changeLoop = (val: string) => {
	console.log(val)
	loopNum.value = parseInt(val)
}
const changeProfitable = (val: string) => {
	console.log(val, 'profit')
	profit.value = val
}
const changeProfitPercentage = (data: any) => {
	profitPer.value = data
}
const changeLossPercentage = (data: any) => {
	lossPer.value = data
}
const changeLoss = (val: string) => {
	console.log(val, 'loss')
	loss.value = val
}
const changeAmount = (val: string) => {
	console.log(val)
	amount.value = val
	calculateProfit()
}
const changeMode = (val: string) => {
	type.value = val
	resultArr = []
	showBet.value = true
	if (val === 'auto') {
		isBtnAutoDisabled.value = true
		console.log(PayoutType?.AUTO)
		minesGames?.updatePayoutType(PayoutType?.AUTO)
		minesGames?.resetAll()
		// 开始游戏
		minesGames?.gameStart(true)
	} else {
		isBtnAutoDisabled.value = false
		minesGames?.updatePayoutType(PayoutType?.MANUAL)
		minesGames?.resetAll()
		// 开始游戏
		minesGames?.gameStart(false)
	}
	isDisabled.value = false
}
</script>

<style lang="scss" scoped>
.yingli {
	display: flex;
	justify-content: space-between;
	height: 18px;
}
.yingli1,
.yingli2 {
	color: var(--text-396-a-5-aa, #96a5aa);
	text-align: right;
	font-style: normal;
	font-weight: 600;
	line-height: 18px; /* 150% */
}
.input-style {
	box-shadow:
		0 1px 3px 0 rgba(0, 0, 0, 0.2),
		0 1px 2px 0 rgba(0, 0, 0, 0.12);
	:deep(.n-input__input > .n-input__input-el) {
		height: 100% !important;
	}
}
.f-style {
	font-weight: 600;
}
.h-group-t {
	height: 12px;
}
.b-shadow {
	box-shadow:
		0 1px 3px 0 rgba(0, 0, 0, 0.2),
		0 1px 2px 0 rgba(0, 0, 0, 0.12);
}
.random-style {
	border-radius: 8px;
	background: #3e4c68;
}
</style>
